package com.chacanks.common.util;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import com.chacanks.common.exception.session.SessionNotFoundException;
import com.chacanks.system.user.User;

/**
 * <pre>
 * 세션관련 유틸리티
 * </pre>
 * @author : Lee Kang-Sun
 * @Date : 2013. 1. 8.
 */
public class SessionUtils {

	private static String USER_SESSION_NAME = "#CHACANKS_USER_SESSION#";
	
	/**
	 * <pre>
	 * 세션에 있는 사용자 시퀀스 정보
	 * </pre>
	 * @author : Lee Kang-Sun
	 * @Date : 2013. 1. 8.
	 * @return
	 * @throws Exception
	 */
	public static String getSessionUserSeq() throws Exception{
		return ((User)getUserSession()).getUserSeq();
	}
	
	/**
	 * <pre>
	 * 사용자 정보 세션을 입력(기존 사용자 세션은 삭제함)
	 * </pre>
	 * @author : Lee Kang-Sun
	 * @Date : 2013. 1. 8.
	 * @param userSession
	 * @throws Exception
	 */
	public static void setUserSession(Object userSession) throws Exception{
		removeSession(USER_SESSION_NAME);
		setSession(USER_SESSION_NAME, userSession);
	}
	
	/**
	 * <pre>
	 * 사용자 정보 세션을 가져옴
	 * </pre>
	 * @author : Lee Kang-Sun
	 * @Date : 2013. 1. 8.
	 * @return
	 * @throws SessionNotFoundException
	 */
	public static User getUserSession() throws SessionNotFoundException{
		try {
			User user = (User)getSession(USER_SESSION_NAME);
			
			if(user == null) 
				throw new NullPointerException();			
			return user;
		} catch (Exception e) {
			throw new SessionNotFoundException("user session not found.");
		}
	}
	
	/**
	 * <pre>
	 * Session ID 가져오기
	 * </pre>
	 * @author : Lee Kang-Sun
	 * @Date : 2013. 1. 8.
	 * @return
	 * @throws Exception
	 */
	public static String getSessionId() throws Exception  {
		return RequestContextHolder.getRequestAttributes().getSessionId();
	}

	/**
	 * <pre>
	 * Session 가져오기
	 * </pre>
	 * @author : Lee Kang-Sun
	 * @Date : 2013. 1. 8.
	 * @param sessionName
	 * @return
	 * @throws Exception
	 */
	public static Object getSession(String sessionName) throws Exception {
		return (Object)RequestContextHolder.getRequestAttributes().getAttribute(sessionName, RequestAttributes.SCOPE_SESSION);
	}

	/**
	 * <pre>
	 * Session 저장
	 * </pre>
	 * @author : Lee Kang-Sun
	 * @Date : 2013. 1. 8.
	 * @param sessionName
	 * @param sessionObject
	 * @throws Exception
	 */
	public static void setSession(String sessionName, Object sessionObject) throws Exception {
		RequestContextHolder.getRequestAttributes().setAttribute(sessionName, sessionObject, RequestAttributes.SCOPE_SESSION);
	}

	/**
	 * <pre>
	 * Session 삭제
	 * </pre>
	 * @author : Lee Kang-Sun
	 * @Date : 2013. 1. 8.
	 * @param sessionName
	 * @throws Exception
	 */
	public static void removeSession(String sessionName) throws Exception {
		RequestContextHolder.getRequestAttributes().removeAttribute(sessionName, RequestAttributes.SCOPE_SESSION);
	}

}
